package com.gome.oa;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.gome.oa.model.Day;
import com.gome.oa.model.OriginalData;
import com.gome.oa.util.DateUtil;

/**
 *
 * @author: tang li
 * @date: 2016年8月6日
 * @desc: 
 *
 */
public class TimeCalculator {
	
	private Date min(Date date1, Date date2) throws ParseException {
		return date1.after(date2) ? date2 : date1;
	}
	
	private Date max(Date date1, Date date2) throws ParseException {
		return date1.after(date2) ? date1 : date2;
	}
	
	public List<Day> calculate(List<OriginalData> list) throws Exception {
		
		Collections.sort(list);
		
		Map<String, Day> map = new TreeMap<>();
		
		for(OriginalData data : list) {
			Date date = DateUtil.parse(data.getTime().substring(0, data.getTime().lastIndexOf(":")));
			String dateStr = DateUtil.format1(date);
			Day day = map.get(dateStr);
			if(day == null) {
				day = new Day();
				day.setMinDate(date);
				map.put(dateStr, day);
			}
			else {
				day.setMaxDate(date);
			}
		}
		
		return new ArrayList<Day>(map.values());
		//return calculate(map);
	}

	private List<Day> calculate(Map<String, Day> map) {
		HolidayManagement holidayManagement = new HolidayManagement();
		List<Day> result = new ArrayList<Day>();
		Iterator<String> it = map.keySet().iterator();
		while(it.hasNext()) {
			String dateStr = it.next();
			Day day = map.get(dateStr);
			long diff = (day.getMaxDate().getTime() - day.getMinDate().getTime())/1000;
			int hour = (int)diff/3600;
			//假期&大于1小时
			if(holidayManagement.isHoliday(day.getMinDate()) && hour >= 1) {
				day.setOffDate(day.getMinDate());
				day.setHour(hour);
				result.add(day);
			}
			else if(hour > 9) {//平时大于9小时
				Calendar offworkTime = Calendar.getInstance();
				offworkTime.setTime(day.getMinDate());
				offworkTime.add(Calendar.HOUR_OF_DAY, 9);
				day.setOffDate(offworkTime.getTime());
				day.setHour(hour - 9);
				result.add(day);
			}
		}
		
		return result;
	}

}
